package com.nageffer.shortlink.admin.common.biz.user;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;

/**
 * 用户信息传输过滤器
 */
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {

    /**
     * 重构：只在请求头中拿到用户信息，并放入上下文中即可
     */
    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String username = httpServletRequest.getHeader("username");
        if (StrUtil.isNotBlank(username)) {
            String userId = httpServletRequest.getHeader("userId");
            String realName = httpServletRequest.getHeader("realName");
            UserInfoDTO userInfoDTO = new UserInfoDTO(userId, username, realName);
            UserContext.setUser(userInfoDTO);
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            //清除上下文中的用户信息
            UserContext.removeUser();
        }
    }

//    private final StringRedisTemplate stringRedisTemplate;
//
//    //定义白名单
//    private static final List<String> IGNORE_URI = Lists.newArrayList(
//            "/api/short-link/admin/v1/user/login", //用户登陆
//            "/api/short-link/admin/v1/user/has-username" //检测用户是否存在
//    );
//
//    @SneakyThrows
//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
//        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
//        //拿到请求的URI
//        String requestURI = httpServletRequest.getRequestURI();
//
//        //查看该请求是否是白名单
//        if (!IGNORE_URI.contains(requestURI)) {
//            String method = httpServletRequest.getMethod();
//            //对于用户注册的请求，因为使用了resultful风格，也需要判断请求方式
//            if (!(Objects.equals(requestURI, "/api/short-link/admin/v1/user") && Objects.equals(method, "POST"))) {
//                //在请求头中拿到username和token
//                String username = httpServletRequest.getHeader("username");
//                String token = httpServletRequest.getHeader("token");
//
//                //username和token都不能为空
//                if (!StrUtil.isAllNotBlank(username, token)) {
//                    //也可以这样写
//                    // httpServletResponse.getWriter().write(JSON.toJSONString(Results.failure(new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL))));
//                    returnJson(httpServletResponse, JSON.toJSONString(Results.failure(new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL))));
//                    return;
//                }
//
//                //从redis中拿到登陆用户的信息
//                Object userInfoJsonStr;
//                try {
//                    userInfoJsonStr = stringRedisTemplate.opsForHash().get("login_" + username, token);
//                    if (userInfoJsonStr == null) {
//                        throw new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL);
//                    }
//                } catch (Exception ex) {
//                    returnJson(httpServletResponse, JSON.toJSONString(Results.failure(new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL))));
//                    return;
//                }
//
//                //把用户信息存到Threadlocal中
//                UserInfoDTO userInfoDTO = JSON.parseObject(userInfoJsonStr.toString(), UserInfoDTO.class);
//                UserContext.setUser(userInfoDTO);
//            }
//        }
//
//        try {
//            filterChain.doFilter(servletRequest, servletResponse);
//        } finally {
//            //清除Threadlocal中的用户信息
//            UserContext.removeUser();
//        }
//
//    }
//
//    /**
//     * 把结果以流的形式写到前端
//     * 因为filter是JavaWeb提供的技术，是在所有请求之前，spring是捕获不到filter抛出的异常的
//     */
//    private void returnJson(HttpServletResponse response, String json) throws Exception {
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("text/html; charset=utf-8");
//        try (PrintWriter writer = response.getWriter()) {
//            writer.print(json);
//        }
//    }

}